// 用户相关的状态管理
import {createSlice} from "@reduxjs/toolkit";
import {getToken, removeToken, setToken} from "@/utils";
import {getUserProfile, loginFormAPI} from "@/apis/user";

const userStore=  createSlice({
    name:"user",
    // 数据状态
    initialState:{
        // 这里token值，每次读取localStorage，如果有值，就调用‘token_key’对应的数据
        token:getToken()||'',
        userInfo:{}
    },
    // 同步修改方法
    reducers:{
        setTokenInfo(state, action){
            state.token=action.payload;
        //     localstorage存一份
           setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo=action.payload;
        },
        clearUserInfo(state){
            state.token=''
            state.userInfo={}
            removeToken();
        }
    }
})

// 解构出actionCreater
const {setTokenInfo,setUserInfo,clearUserInfo}=userStore.actions;

// 获取reducer函数
const userReducer=userStore.reducer;

// 异步方法

const fetchLogin=(loginForm)=>{
    return async (dispatch)=>{
      const res= await loginFormAPI(loginForm)
      dispatch(setTokenInfo(res.data.token))
    }
}

// 获取个人用户信息异步方法
const fetchGetUserInfo=()=>{
    return async (dispatch)=>{
        const res=await getUserProfile();
        dispatch(setUserInfo(res.data))
    }
}



export {fetchLogin,fetchGetUserInfo,clearUserInfo,setTokenInfo,setUserInfo}

export default userReducer;
